<?php

namespace mpend\modules\team\models;

use Yii;
use common\helpers\ArrayHelper;
use common\models\workbook\WorkbookRecord;
use common\logics\WorkbookLogic;

/**
 * 班组记工本管理模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class TeamBookDateViewSearch extends WorkbookLogic {

    /**
     * @var string 查询的记工日期
     */
    private $_date;

    /**
     * 记工日期
     * @return string
     */
    public function getDate() {
        if ($this->_date) {
            return $this->_date;
        }
        return date('Y-m-d');
    }

    /**
     * 设置记工日期
     */
    public function setDate($date = null) {
        if (!$date) {
            $date = Yii::$app->request->get('date');
        }
        if ($date) {
            $this->_date = $date;
        }
    }

    /**
     * @inheritdoc
     */
    public function getWorkers() {
        $query = $this->find();
        $query->joinWith([
            'members' => function($q) {
                $q->alias('members')->active();
            }
        ]);
        $query->joinWith([
            'workRecords' => function($q) {
                $q->alias('workRecords')->active();
            }
        ]);
        $query->andWhere([
            'workRecords.id' => null
        ]);
        return $query->debug(true);
    }

    /**
     * @inheritdoc
     */
    public function getBooks() {
        $data = $this->getConditionRecords([
            'date' => $this->date
        ])->all();
        $types = [
            WorkbookRecord::TYPE_WORK => 'work',
            WorkbookRecord::TYPE_LOAN => 'loan',
            WorkbookRecord::TYPE_BALANCE => 'balance',
        ];
        $res = [];
        foreach ($data as $item) {
            $logType = ArrayHelper::getValue($types, $item->type);
            if ($logType === null) {
                continue;
            }
            $amount = $item->amount;
            $nums = 1;
            if ($item->type === WorkbookRecord::TYPE_WORK) {
                $nums = $item->workload;
            }
            if (isset($res[$item->member_id])) {
                $res[$item->member_id]['types'][$logType]['amount'] += $amount;
                $res[$item->member_id]['types'][$logType]['nums'] += $nums;
            } else {
                $res[$item->member_id]['types'][$logType] = [
                    'amount' > $amount,
                    'nums' > $nums,
                ];
                $res[$item->member_id] = [
                    'types' => [],
                    'types' => [],
                ];
            }
        }
        return array_values($res);
    }

    public function fields() {
        return [
            'id',
            'workers',
            'records' => 'books',
        ];
    }

}
